package com.lagou.user.service.impl;

import com.lagou.common.pojo.Token;
import com.lagou.common.pojo.User;
import com.lagou.user.dao.ITokenRepository;
import com.lagou.user.dao.IUserRepository;
import com.lagou.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * created by kirito at 2020/6/23
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private ITokenRepository tokenRepository;

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public boolean isRegistered(String email) {
        User user = userRepository.findByEmail(email);
        return user != null;
    }

    @Override
    public User findByEmailAndPassword(String email, String password) {
        return userRepository.findUserByEmailAndPassword(email, password);
    }

    @Override
    public boolean validateToken(String token) {
        Token t = tokenRepository.findByToken(token);
        return t != null;
    }

    @Override
    public String findEmailByToken(String token) {
        Token t = tokenRepository.findByToken(token);
        return t.getEmail();
    }

    @Override
    public boolean validateUserInfo(String email, String password) {
        // 邮箱格式验证：必须包含@和. 密码验证：长度[6, 18]
        if (!(email.contains("@") && email.contains(".") && password.length() >= 6 && password.length() <= 18)) {
            return false;
        }
        User user = userRepository.findUserByEmailAndPassword(email, password);
        return null != user;
    }
}
